package com.gaozhaoyang.demo;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/*
*  prepareStatement解决sql注入 预编译技术
* */
public class JDBCDemo_02 {
    public static void main(String[] args) {
        //接受请求中携带的数据
        System.out.println("请输入用户名");
        Scanner sc = new Scanner(System.in);
        String username = sc.nextLine();
        System.out.println("请输入密码");
        String password = sc.nextLine();

        //调用业务
        login(username,password);
    }
    private static void login(String username,String password){
        //建立连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        ResultSet rs = null;
        PreparedStatement ps = null;
        Connection con = null;
        try {
            con = dataSource.getConnection();
            String sql = "select * from user where username = ? and password = ?";
            //创建可执行对象
            ps = con.prepareStatement(sql);
            //设置参数
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if (rs.next()){
                System.out.println("登陆成功");
            }else{
                System.out.println("登陆失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            try {
                rs.close();
                ps.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
}
